package com.example.demo.service;

import com.example.demo.util.FtpUtil;
import com.example.demo.util.IDUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class UserService {

    @Value("${ftp.host}")
    private String host;
    // 端口
    @Value("${ftp.port}")
    private int port;
    // ftp用户名
    @Value("${ftp.username}")
    private String userName;
    // ftp用户密码
    @Value("${ftp.password}")
    private String passWord;
    // 文件在服务器端保存的主目录
    @Value("${ftp.basePath}")
    private String basePath;

    public String pictureUpload(MultipartFile uploadFile) {
        try {
            //1、给上传的图片生成新的文件名
            //1.1获取原始文件名
            String oldName = uploadFile.getOriginalFilename();
            //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀
            String newName = IDUtils.genImageName();
            newName = newName + oldName.substring(oldName.lastIndexOf("."));
            //1.3生成文件在服务器端存储的子目录
            String filePath = "images/java";
            //String filePath = "images/"+new DateTime().toString("/yyyy/MM/dd");也可以写成日期子目录的格式


            //3、把图片上传到图片服务器
            //3.1获取上传的io流
            InputStream input = uploadFile.getInputStream();

            //3.2调用FtpUtil工具类进行上传
            boolean result = FtpUtil.uploadFile(host, port, userName, passWord, basePath, filePath, newName, input);
            if (result) {
                return  host+"/images/java/" + newName;  //最后返回访问的url
            } else {
                return "false";
            }
        } catch (IOException e) {
            return "false";
        }
    }


}
